// app/(tabs)/settings.js
import Loading from '@/components/Loading';
import { api } from '@/utils/request/Api';
import { Ionicons } from '@expo/vector-icons';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { router } from 'expo-router';
import React, { useEffect, useState } from 'react';
import { Alert, ScrollView, KeyboardAvoidingView,Platform,StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';
export default function SettingsScreen() {
  const [senderName, setSenderName] = useState('');
  const [senderEmail, setSenderEmail] = useState('');
  const [template, setTemplate] = useState('Hi {name},\n\nI hope this email finds you well...');
  const [loading, setLoading] = useState(false);
 
  useEffect(() => {
    setLoading(true)
    api.get('user/info',{}).then((res) => {
      setLoading(false)
      if(res.code == 1){
        setSenderName(res.data.send_email_name);
        setSenderEmail(res.data.send_from_email);
        setTemplate(res.data.email_temp);
      }
    }).catch(() => {
      setLoading(false)
    })
  }, [])
  const handleSave = () => {
    setLoading(true)
    api.post('user/setting',{data:{send_name:senderName,send_email:senderEmail,template:template}}).then((res) => {
        setLoading(false)
        Alert.alert("Tip","Save success")
    })
    //alert('Settings saved');
  };
  //登出
  const onLogout = () => {
    Alert.alert("Tip","Are you sure to logout?",[
      {
        text: "Cancel",
      },
      {
        text: "ok",
        onPress: () => {
          AsyncStorage.setItem('USER-INFO', '');
          router.push('/');
        }
      }
    ])
  }
  return (
    <KeyboardAvoidingView behavior={Platform.OS == "ios" ? "padding" : "height"} style={styles.container}>
    <ScrollView >
      <Text style={styles.title}>Settings</Text>

      <Text style={styles.sectionTitle}>Sender Information</Text>
      <Text style={styles.sectionDesc}>This information will be used when sending email campaigns</Text>

      <Text style={styles.label}>Sender Name</Text>
      <View style={styles.inputBox}>
        <Ionicons name="person-outline" size={18} color="#888" style={{ marginRight: 8 }} />
        <TextInput value={senderName} onChangeText={setSenderName} style={styles.input} />
      </View>

      <Text style={styles.label}>Sender Email</Text>
      <View style={styles.inputBox}>
        <Ionicons name="mail-outline" size={18} color="#888" style={{ marginRight: 8 }} />
        <TextInput value={senderEmail} onChangeText={setSenderEmail} style={styles.input} keyboardType="email-address" />
      </View>

      <TouchableOpacity disabled={loading} style={styles.saveBtn} onPress={handleSave}>
        <Text style={styles.saveText}>💾 Save Settings</Text>
      </TouchableOpacity>

      <Text style={styles.sectionTitle}>Default Email Template</Text>
      <Text style={styles.sectionDesc}>This template will be pre-filled when creating new campaigns</Text>

      <TextInput
        multiline
        value={template}
        onChangeText={setTemplate}
        style={styles.templateBox}
      />

      <Text style={styles.tip}>Use <Text style={styles.placeholder}>{'{name}'}</Text> as a placeholder for recipient name</Text>
      {loading && <Loading />}
      <TouchableOpacity  style={styles.loginoutBtn} onPress={() => onLogout()}>
        <Text style={styles.saveText}>Login out</Text>
      </TouchableOpacity>
    </ScrollView>
    
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20, backgroundColor: '#fff' },
  title: { fontSize: 22, fontWeight: '600', marginTop: 20, textAlign: 'center' },
  sectionTitle: { marginTop: 30, fontSize: 16, fontWeight: '600' },
  sectionDesc: { fontSize: 13, color: '#666', marginBottom: 10 },
  label: { marginTop: 16, marginBottom: 6, fontWeight: '500' },
  inputBox: {
    flexDirection: 'row', alignItems: 'center', backgroundColor: '#f3f4f6',
    borderRadius: 10, paddingHorizontal: 12, height: 48
  },
  input: { flex: 1, fontSize: 14 },
  saveBtn: {
    backgroundColor: '#3B82F6', paddingVertical: 14, marginTop: 20, borderRadius: 10,
    alignItems: 'center', justifyContent: 'center'
  },
  
  saveText: { color: '#fff', fontWeight: '600' },
  templateBox: {
    backgroundColor: '#f9fafb', marginTop: 12, padding: 14, borderRadius: 10,
    fontSize: 14, minHeight: 100, textAlignVertical: 'top'
  },
  tip: { fontSize: 12, color: '#666', marginTop: 6 },
  placeholder: { fontWeight: '600', color: '#3B82F6' },
  loginoutBtn:{
    backgroundColor: '#000000', paddingVertical: 14, marginTop: 20, borderRadius: 10,
    alignItems: 'center', justifyContent: 'center',marginBottom:25,
  }
});